from fastapi import APIRouter
from pydantic import BaseModel

from DataModels.database import User
from DataModels.share import RespInfo, RespResultCode, StatusInfo, TokenPayload
from config import logger
from utils.share import timestamp
from utils.token import decode_token, generate_token


class RegisterRequest(BaseModel):
    code: str  # 此code为验证码正确后，返回的临时密文（== token）
    password: str


# response =>
# {token: str}


register_router = APIRouter(prefix="/register")


@register_router.post("", response_model=RespInfo)
async def register(data: RegisterRequest):
    try:
        token = decode_token(data.code)
    except Exception as e:
        logger.error(e)
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.DataCorrupted,
                msg="解密加密code失败",
            )
        )
    phone = token.phone
    user = await User.find_one(User.phone == phone)
    if not user:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.PhoneNotFound,
                msg="未找到手机号，注册失败",
            )
        )
    user.password = data.password
    await user.save()  # type: ignore
    return RespInfo(
        status=StatusInfo(
            code=RespResultCode.Success,
            msg="注册成功",
        ),
        token=generate_token(TokenPayload(phone=phone, createTime=timestamp())),
    )
